package com.example.voicechat

import android.content.Context
import android.graphics.Bitmap
import android.util.Base64
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import org.json.JSONArray
import java.io.ByteArrayOutputStream

class ImageRecognitionManager(private val context: Context) {
    interface ImageRecognitionListener {
        fun onResult(result: String)
        fun onError(error: String)
        fun onProgress(progress: Int)
    }

    companion object {
        private const val API_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
        private const val API_KEY = "sk-06836f9701fc43d9aeb0e8022e35d5f6"  // 替换为你的阿里云API密钥
        private const val MAX_IMAGE_SIZE = 1024 * 1024  // 1MB
        private const val COMPRESS_QUALITY = 80  // JPEG压缩质量
    }

    private val client = OkHttpClient()
    private var currentCall: Call? = null

    fun recognizeImage(bitmap: Bitmap, listener: ImageRecognitionListener) {
        try {
            listener.onProgress(0)
            val resizedBitmap = resizeBitmapIfNeeded(bitmap)
            listener.onProgress(20)
            
            val base64Image = bitmapToBase64(resizedBitmap)
            listener.onProgress(40)
            
            // 构建请求体
            val jsonBody = JSONObject().apply {
                put("model", "qwen-vl-plus")
                put("messages", JSONArray().apply {
                    put(JSONObject().apply {
                        put("role", "user")
                        put("content", JSONArray().apply {
                            put(JSONObject().apply {
                                put("type", "text")
                                put("text", "识别最中间的完整的题目，并整理输出文字")
                            })
                            put(JSONObject().apply {
                                put("type", "image_url")
                                put("image_url", JSONObject().apply {
                                    put("url", "data:image/jpeg;base64,$base64Image")
                                })
                            })
                        })
                    })
                })
            }

            val request = Request.Builder()
                .url(API_URL)
                .addHeader("Authorization", "Bearer $API_KEY")
                .addHeader("Content-Type", "application/json")
                .post(
                    jsonBody.toString()
                        .toRequestBody("application/json".toMediaType())
                )
                .build()

            currentCall = client.newCall(request)
            currentCall?.enqueue(object : Callback {
                override fun onFailure(call: Call, e: java.io.IOException) {
                    if (!call.isCanceled()) {
                        listener.onError("图片识别请求失败: ${e.message}")
                    }
                }

                override fun onResponse(call: Call, response: Response) {
                    listener.onProgress(80)
                    val responseBody = response.body?.string()
                    if (response.isSuccessful && responseBody != null) {
                        try {
                            val jsonResponse = JSONObject(responseBody)
                            val choices = jsonResponse.optJSONArray("choices")
                            if (choices != null && choices.length() > 0) {
                                val message = choices.getJSONObject(0)
                                    .getJSONObject("message")
                                val content = message.getString("content")
                                if (content.isNotEmpty()) {
                                    listener.onResult(content)
                                } else {
                                    listener.onError("识别结果为空")
                                }
                            } else {
                                listener.onError("无法获取识别结果")
                            }
                        } catch (e: Exception) {
                            listener.onError("解析识别结果失败: ${e.message}")
                        }
                    } else {
                        listener.onError("图片识别失败: ${response.code}")
                    }
                    listener.onProgress(100)
                }
            })
        } catch (e: Exception) {
            listener.onError("处理图片失败: ${e.message}")
        }
    }

    fun cancel() {
        currentCall?.cancel()
    }

    private fun bitmapToBase64(bitmap: Bitmap): String {
        // 压缩图片到合适大小
        var compressQuality = COMPRESS_QUALITY
        val outputStream = ByteArrayOutputStream()
        
        do {
            outputStream.reset()
            bitmap.compress(Bitmap.CompressFormat.JPEG, compressQuality, outputStream)
            compressQuality -= 10
        } while (outputStream.size() > MAX_IMAGE_SIZE && compressQuality > 0)

        LogUtils.e("ImageRecognition", "图片大小: ${outputStream.size()} bytes")
        return Base64.encodeToString(outputStream.toByteArray(), Base64.NO_WRAP)
    }

    private fun resizeBitmapIfNeeded(bitmap: Bitmap, maxWidth: Int = 1024, maxHeight: Int = 1024): Bitmap {
        val width = bitmap.width
        val height = bitmap.height
        
        if (width <= maxWidth && height <= maxHeight) {
            return bitmap
        }

        val ratioBitmap = width.toFloat() / height.toFloat()
        val ratioMax = maxWidth.toFloat() / maxHeight.toFloat()

        var finalWidth = maxWidth
        var finalHeight = maxHeight
        if (ratioMax > ratioBitmap) {
            finalWidth = (maxHeight.toFloat() * ratioBitmap).toInt()
        } else {
            finalHeight = (maxWidth.toFloat() / ratioBitmap).toInt()
        }

        return Bitmap.createScaledBitmap(bitmap, finalWidth, finalHeight, true)
    }

    private fun saveImageForDebug(bitmap: Bitmap) {
        try {
            val fileName = "recognition_${System.currentTimeMillis()}.jpg"
            context.openFileOutput(fileName, Context.MODE_PRIVATE).use { stream ->
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
            }
            LogUtils.e("ImageRecognition", "图片已保存: $fileName")
        } catch (e: Exception) {
            LogUtils.e("ImageRecognition", "保存图片失败: ${e.message}")
        }
    }
} 